<?php
namespace StarCloud\Library;

use Phalcon\Di;
use Phalcon\Events\Manager;
use Phalcon\Mvc\User\Plugin;

class SystemEventsComponent extends Plugin
{
    protected $eventsManager;

    protected $listenEvents = [];

    public function __construct($events)
    {
        $this->eventsManager = new Manager();
        foreach ($events as $event => $listeners) {
            foreach ($listeners as $listener) {
                $this->eventsManager->attach($event, $listener);
            }
        }
    }

    public function addEvent($eventName, $params)
    {
        $this->listenEvents[] = [$eventName, $params];

        if (ENVIRONMENT != 'production') {
            Di::getDefault()->getShared('logger')->info('[SystemEvent] name: ' . $eventName);
        }
    }

    public function executeAllEvents()
    {
        foreach ($this->listenEvents as $event) {
            try {
                $this->eventsManager->fire($event[0], $this, $event[1]);
            } catch (\Exception $e) {
                // do nothing
            }
        }

        // 只执行一次
        $this->listenEvents = [];
    }
}
